package com.xca.is.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.google.android.material.textfield.TextInputEditText;
import com.xca.is.R;
import com.xca.is.databinding.ActivityCourierBinding;
import com.xca.is.entity.Courier;
import com.xca.is.http.HttpConnect;
import com.xca.is.model.CourierModel;
import com.xca.is.utils.EditTextUtils;
import com.xca.is.utils.WebViewScriptUtils;

public class CourierActivity extends AppCompatActivity implements HttpConnect {
    private ActivityCourierBinding binding ;
    private CourierModel model ;
    private ViewModelProvider provider ;
    private MutableLiveData<Courier> liveData ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCourierBinding.inflate(getLayoutInflater());
        EdgeToEdge.enable(this);
        setContentView(binding.getRoot());
        binding.courierProgress.setVisibility(View.GONE);
        binding.courierQuery.setVisibility(View.GONE);
        binding.courierClean.setVisibility(View.GONE);
        binding.courierV1.setVisibility(View.GONE);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });


        int[] ints = new int[]{10,18} ;
        WebViewScriptUtils.htmlContent(ints,binding.courierWeb);

        provider = new ViewModelProvider(this) ;
        model = provider.get(CourierModel.class) ;
        model.setModel(this);
        liveData = (MutableLiveData<Courier>) model.getLiveData() ;
        liveData.observe(this, new Observer<Courier>() {
            @Override
            public void onChanged(Courier courier) {
                if (courier!=null){
                    showData(courier);
                }else {
                    binding.courierContent.setText("查询失败......");
                }
            }
        });
        onClickListener();
        editOnChange();
    }

    private void showData(@NonNull Courier courier){
        Glide.with(this)
                .load(courierLogo(courier.getName()))
                .error(R.drawable.kuaidi)
                .fitCenter()
                .into(binding.courierImg);
        binding.courierName.setText(courier.getName());
        binding.courierTips.setText(courier.getDh());
        binding.courierContent.setText(courier.getMsg());
        binding.courierCopy.setText("复制");
        binding.courierV1.setVisibility(View.VISIBLE);
    }

    private void onClickListener(){
        binding.courierQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String id = binding.courierId.getText().toString().trim();
                String phone = binding.courierPhone.getText().toString().trim();
                if (id.isEmpty()){
                    binding.courierId.setError("请输入快递单号");
                    return;
                }
                if (id.length() < 6 || id.length() > 20) { // 假设快递单号长度在6到20之间
                    binding.courierId.setError("快递单号长度应在6到20位之间");
                    return;
                }
                if (phone.isEmpty()){
                    binding.courierPhone.setError("请输入手机尾号后四位");
                    return;
                }
                if (phone.length() != 4) { // 手机尾号后四位
                    binding.courierPhone.setError("请输入正确的手机尾号后四位");
                    return;
                }
                try {
                    model.getData(id, phone);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(CourierActivity.this, "网络请求失败，请稍后再试", Toast.LENGTH_SHORT).show();
                }
            }
        });
        binding.courierCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String copyText = binding.courierTips.getText().toString() ;
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE) ;
                ClipData clipData = ClipData.newPlainText("courierId", copyText) ;
                if (clipData == null){
                    return;
                }
                clipboard.setPrimaryClip(clipData);
                Toast.makeText(CourierActivity.this, "文本已复制", Toast.LENGTH_SHORT).show();
            }
        });

        binding.courierClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.courierId.setText("");
                binding.courierPhone.setText("");
                EditTextUtils.clearFocus(binding.courierId);
                EditTextUtils.clearFocus(binding.courierPhone);
            }
        });
    }
private void editOnChange(){
    TextInputEditText[] inputs = new TextInputEditText[] {binding.courierId, binding.courierPhone};
for (TextInputEditText input : inputs) {
    input.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (charSequence.length() > 0) {
                binding.courierClean.setVisibility(View.VISIBLE);
                binding.courierQuery.setVisibility(View.VISIBLE);
            } else {
                binding.courierClean.setVisibility(View.GONE);
                binding.courierQuery.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {
            String text = editable.toString();
            if (input == binding.courierPhone) {
                if (!text.matches("\\d*")) {
                    input.setError("请输入有效的手机号码");
                } else if (text.length() > 4) {
                    input.setError("手机号码过长");
                }
            }
        }
    });
}

}

    private String courierLogo(String name){
        String logo = "";
        switch (name){
            case "京东快递" :
                logo = "https://ts4.cn.mm.bing.net/th?id=ODLS.40c9c775-16dc-47f7-98ab-1ea88aa4899b&w=32&h=32&qlt=91&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "顺丰快递" :
                logo = "https://ts3.cn.mm.bing.net/th?id=ODLS.5653dd97-bed7-4f12-81f9-d42f4cdeb989&w=32&h=32&qlt=91&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "中通快递" :
                logo = "https://ts2.cn.mm.bing.net/th?id=ODLS.bc4ae6d4-678f-47b8-9d4c-8003fe1352f3&w=32&h=32&qlt=93&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "圆通快递" :
                logo = "https://ts2.cn.mm.bing.net/th?id=ODLS.da89ffd3-1a22-4fbe-9f97-56c858b7ac15&w=32&h=32&qlt=92&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "申通快递" :
                logo = "https://ts1.cn.mm.bing.net/th?id=ODLS.4b60a191-752b-4099-916a-87d90a59f85c&w=32&h=32&qlt=93&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "韵达快递" :
                logo = "https://ts1.cn.mm.bing.net/th?id=ODLS.18326dab-3391-4336-b2a9-fcb70ba7734c&w=32&h=32&qlt=92&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "EMS" :
            case "邮政快递" :
                logo = "https://ts1.cn.mm.bing.net/th?id=ODLS.b51497cc-57d2-4b34-bdd6-9191db38e6a8&w=32&h=32&qlt=93&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "极兔快递" :
                logo = "https://ts2.cn.mm.bing.net/th?id=ODLS.58b1f6a8-2528-47c8-bc28-3b66f14b77fd&w=32&h=32&qlt=92&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "百世快递" :
                logo = "https://ts3.cn.mm.bing.net/th?id=ODLS.79710a84-9925-4bd3-aaf8-b601b70286e4&w=32&h=32&qlt=92&pcl=fffffa&o=6&pid=1.2" ;
                break;
            case "德邦快递" :
                logo = "https://ts2.cn.mm.bing.net/th?id=ODLS.ab1172d9-6b7e-4895-9a30-3f8fc03516e9&w=32&h=32&qlt=92&pcl=fffffa&o=6&pid=1.2" ;
                break;
            default:
                logo = "https://ts2.cn.mm.bing.net/th?id=ODLS.f3d2e28e-c6f5-4893-85f3-d636894006df&w=32&h=32&qlt=91&pcl=fffffa&o=6&pid=1.2" ;
                break;
        }
        return logo ;
    }

    @Override
    public void Loading(boolean loading) {
        binding.courierProgress.setVisibility(loading?View.VISIBLE:View.GONE);
    }

    @Override
    public void Success(Object object) {

    }

    @Override
    public void Fail(String... msg) {

    }

    @Override
    public void Error(String msg) {

    }

    @Override
    public void Complete() {
        binding.courierProgress.setVisibility(View.GONE);
    }

    @Override
    public void Timeout() {

    }

    @Override
    public void TokenError() {

    }
}